package com.lyq.interaction.service;

import com.lyq.interaction.mapper.FriendMapper;
import com.lyq.interaction.mapper.UserMapper;
import com.lyq.interaction.model.Friend;
import com.lyq.interaction.model.User;
import com.lyq.interaction.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private FriendMapper friendMapper;

    /**
     * 获取用户头像路径
     * @param userId 用户id
     * @return 返回用户头像路径
     */
    public String getPhoto(Integer userId) {
        return userMapper.getUserPhoto(userId);
    }

    public User getUserInfo(String userName) {
        return userMapper.getUserByName(userName);
    }

    public boolean creatUser(String userName, String password) {
        //加密密码
        password = MD5Util.puzzle(password);
        try{
            if (userMapper.creatUser(userName, password) == 1) {
                return true;
            }
        }catch (DuplicateKeyException e) {
            log.info("该用户已存在 userName: {}", userName);
        }
        return false;
    }

    //搜索用户
    public List<User> getUserListByName(String str, Integer userId) {
        List<User> users = userMapper.getUserListByName(str);

        if (users.isEmpty()) {
            return null;
        }
        //如果用户是当前用户的好友则将id设为0
        for (User user : users) {
            if (user.getUserId().equals(userId) || friendMapper.isFriend(userId, user.getUserId()) == 1) {
                user.setUserId(0);
            }
        }
        return users;
    }

    public void addPhoto(Integer userId, String path) {
        if (userMapper.addPhoto(userId, path) != 1) {
            throw new RuntimeException("设置头像失败");
        }
    }

    /**
     * @param userId 用户id
     * @param password 待修改的新密码
     */
    @Transactional
    public boolean setPassword(int userId, String password) {
        if (1 != userMapper.setPassword(userId, password)) {
            throw new RuntimeException("密码修改异常");
        }
        return true;
    }

    public boolean setUserName(int id, String name) {
        if (1 != userMapper.setUserName(id, name)) {
            throw new RuntimeException("用户名修改异常");
        }
        return true;
    }
}
